import axios from 'axios'
import {getCookie,removeCookie} from './cookie'
import { message } from '@/utils/element'
import {VXETable} from 'vxe-table'

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, 
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})
let source = axios.CancelToken.source()

// request拦截器
service.interceptors.request.use(config => {
  
  let token = getCookie('token')
  if (token) {
    config.headers['Authorization'] = token
	}
  config.headers['X-Request-Id'] = 1
  config['CancelToken']=source.token
  return config
}, error => {
  Promise.reject(error)
})
// 响应拦截 need_login '{"page":1,"limit":1}' 登录页面判断是否后台token在线
service.interceptors.response.use(res => {
 let isLogin = window.location.href.indexOf('login')>=0
    if(!res.data.success
        && res.data.message=="need_login"
        && !isLogin
        && res.config.data !='{"page":1,"limit":1}')
        {
          VXETable.modal.alert({
              id:'need_login_box',
              title:'提示',
              content:'长时间未操作，请重新登录?',
          }).then(async (type)=>{
            if(type=='confirm'){
                removeCookie('userInfo')
                sessionStorage.removeItem('activeValue')
                location.href = '#/login'
            }
          })
  }
  return res
}, error => {
  message('无法连接网络，请检查您的网络连接',3)
  return Promise.resolve({data:{success:false,data:[],message:'无法连接网络，请检查您的网络连接'}})
})

export default service

